﻿using OA.Core;
using OA.Model;
using OA.Web.Areas.Member.Controllers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;

using Z.EntityFramework.Plus;
using Microsoft.AspNetCore.Mvc;
using OA.Web.Attribute;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using OA.Core.Helper;
using OA.Model.DB;
using OA.Core.Model;

namespace OA.Web.Areas.Management.Controllers
{
    [Area("Management")]
    public class EmployeeController : BaseMemberController
    {
        private IMemoryCache _cache;
        public EmployeeController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
        }

        [HttpGet]
        [MyActionFilter("205003", "职员管理", "人力资源管理", true, "iconzaizhiyuangong2")]
        public IActionResult Index(string keyword)
        {
            ViewBag.Keyword = keyword;
            return View();
        }

        [MyActionFilter("205003", "职员管理")]
        public IActionResult GetData(string keyWord, int page = 1, int limit = 12)
        {            
            Expression<Func<Employee, bool>> where = m => true;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = m => m.EmpName.Contains(keyWord);
            }             
            Expression<Func<Employee, int>> order = m => m.ID;
            PageList<SimpleEmployee> pageList = this.GetPageList<Employee, SimpleEmployee>(where, page, limit, SimpleEmployee.Map, order, 1);
            var result = new
            {
                code = "0",
                msg = "",
                count = pageList.RowCount,
                data = pageList.List
            };
            return Json(result);
        }



        [HttpGet]
        [MyActionFilter("205003001", "添加职员", "职员管理", false, "")]
        public IActionResult Create()
        {
            ViewBag.PositionLevel = base.BaseConfig.PositionLevel.Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries).Select(m => new ListItem() { Text = m, Value = m }).ToList();
            return View(new Employee());
        }

        [HttpPost]
        [MyActionFilter("205003001", "添加职员", "职员管理", false, "")]
        public IActionResult Create(Employee info)
        {
            BaseResult baseResult = new BaseResult();
            try
            {
                if (!ModelState.IsValid)
                {
                    baseResult.State = 400;
                    baseResult.Msg= this.GetModelStateError(ModelState);                     
                    return Json(baseResult);
                }
                info.Status = 1;
                info.Password = info.SID.LastNToString(8).ToMd5String();
                info.Token = Guid.NewGuid().ToString("N");
                this.AddInfo<Employee>(info);
                baseResult.Msg = "url:/Management/Employee/Show?empID=" + info.EmpID;
                return Json(baseResult);
            }
            catch(Exception ex)
            {
                baseResult.State = 400;
                baseResult.Msg = ex.Message;
                return Json(baseResult);
            }
            
        }




        [HttpGet]
        [MyActionFilter("205003002", "编辑职员信息", "职员管理", false, "")]
        public IActionResult Edit(int id)
        {
            ViewBag.PositionLevel = base.BaseConfig.PositionLevel.Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries).Select(m => new ListItem() { Text = m, Value = m }).ToList();
            Employee infoEmployee = this.GetInfo<Employee>(id);
            if (infoEmployee == null)
            {
                return View("Create",new Employee());
            }
            else
            {
                return View("Create",infoEmployee);
            }
        }

        [HttpPost]
        [MyActionFilter("205003002", "编辑职员信息", "职员管理", false, "")]
        public IActionResult Edit(int id, Employee info)
        {
            BaseResult baseResult = new BaseResult();
            try
            {
                Employee oldInfo = this.GetInfo<Employee>(id);
                if (!ModelState.IsValid)
                {
                    baseResult.State = 400;
                    baseResult.Msg = this.GetModelStateError(ModelState);
                    return Json(baseResult);
                }
                this.Update<Employee>(oldInfo, info, new string[] { }, new string[] { "EmpID", "Status", "Password", "Token" });
                baseResult.Msg = "更新成功";
                return Json(baseResult);
            }
            catch(Exception ex)
            {
                baseResult.State = 400;
                baseResult.Msg = ex.Message;
                return Json(baseResult);
            }
            
        }

        [MyActionFilter("205003003", "职员排序", "职员管理", false, "")]
        public IActionResult SetSort(int id, int sort)
        {             
            try
            {
                Employee infoEmployee = this.GetInfo<Employee>(id);
                if (infoEmployee == null)
                {
                    return Json(new { State = 400, Message = "没有找到相关的记录" });
                }
                Employee updateEmployee = new Employee();
                updateEmployee.Sort = sort;
                this.Update<Employee>(infoEmployee, updateEmployee, new string[] { "Sort" });
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }

        [MyActionFilter("205003004", "启用职员", "职员管理", false, "")]
        public IActionResult Enabled(int id)
        {
            try
            {
                Employee infoEmployee = this.GetInfo<Employee>(id);
                if (infoEmployee == null)
                {
                    return Json(new { State = 400, Message = "没有找到相关的记录" });
                }
                Employee updateEmployee = new Employee();
                updateEmployee.Status = 1;
                this.Update<Employee>(infoEmployee, updateEmployee, new string[] { "Status" });
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }


        [HttpGet]
        [MyActionFilter("205003005", "禁用职员", "职员管理", false, "")]
        public IActionResult Disable(int id)
        {             
            try
            {
                Employee infoEmployee = this.GetInfo<Employee>(id);
                if (infoEmployee == null)
                {
                    return Json(new { State = 400, Message = "没有找到相关的记录" });
                }
                Employee updateEmployee = new Employee();
                updateEmployee.Status = -1;
                this.Update<Employee>(infoEmployee, updateEmployee, new string[] { "Status" });
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }

        [HttpGet]
        [MyActionFilter("205003006", "删除职员", "职员管理", false, "")]
        public IActionResult Delete(int id)
        {
            try
            {
                this.Delete<Employee>(id);
                return Json(new { State = 200, Message = "" });
            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }


        [HttpGet]
        [MyActionFilter("205003007", "职员权限管理", "职员管理", false, "")]
        public IActionResult Permission(string empID)
        {

            List<SimplePermissionGroup> listPermissionGroup = this.dbContextFactory.DbContext.PermissionGroup.Where(m => m.Status != -1).Select(SimplePermissionGroup.Map).ToList();
            List<int> currentPermissions = this.dbContextFactory.DbContext.UserPermissionGroup.Where(m => m.Status != -1&&m.EmpID== empID).Select(m=>m.PermissionGroupID).ToList();
            listPermissionGroup.Where(m => currentPermissions.Contains(m.ID)).ToList().ForEach(m => m.IsSelected = true);
            ViewBag.EmpID = empID;
            return View(listPermissionGroup);
        }


        [MyActionFilter("205003008", "重置密码", "职员管理", false, "")]
        [HttpGet]
        public IActionResult ResetPassword(int id)
        {
            try
            {
                var empID = this.dbContextFactory.DbContext.Employee.Where(m => m.ID == id).Select(m => m.EmpID).FirstOrDefault();
                if (string.IsNullOrWhiteSpace(empID))
                {
                    return Json(new { State = 400, Message = "没有找到当前用户" });
                }
                string passWord = CommonHelper.GetRandomString(10, true, true, true, true, "@!#%");
                // (userName.ToLower() + password).ToMd5String()
                string mm = (empID.ToLower() + passWord).ToMd5String();
                this.dbContextFactory.DbContext.Database.ExecuteSqlCommand($"Update Employee set Password='{mm}' where EmpID='{empID}'");
                return Json(new { State = 200, Message = passWord });
            }
            catch (Exception ex)
            {
                MyStatic.ExecptionQueue.Enqueue(ex);
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }

        [HttpGet]
        [MyActionFilter("205003009", "设置岗位", "职员管理", false, "")]
        public IActionResult SetPosition(string empID)
        {
            ViewBag.PositionID = 0;
            ViewBag.DepartmentID = 0;
            ViewBag.EmpID = empID;
            return View();
        }

        [HttpPost]
        [MyActionFilter("205003009", "设置岗位", "职员管理", false, "")]
        public IActionResult SetPosition(string empID, int PositionID, string StartTime, string EndTime)
        {
            BaseResult result = new BaseResult();
            EmployeePosition employeePosition = new EmployeePosition();
            employeePosition.EmpID = empID;
            employeePosition.EndTime = EndTime;
            employeePosition.PositionID = PositionID;
            employeePosition.StartTime = StartTime;
            employeePosition.Status = 1;
            string empName = this.dbContextFactory.DbContext.Employee.Where(m => m.EmpID == empID).Select(m => m.EmpName).FirstOrDefault();
            employeePosition.EmpName = empName;
            this.AddInfo<EmployeePosition>(employeePosition);
            result.Msg = "岗位设置成功";
            return Json(result);
        }


        //AddPermissionGroup?empID=@empID&PermissionGroupID=" + data.value+"&status="+status;
        [HttpGet]
        [MyActionFilter("205003007", "职员权限管理", "职员管理", false, "")]
        public IActionResult AddPermissionGroup(string empID,int permissionGroupID,int status)
        {
            BaseResult baseResult = new BaseResult();

            if(this.dbContextFactory.DbContext.Employee.Where(m => m.EmpID == empID).Select(m => m.ID).FirstOrDefault()==0)
            {
                baseResult.State = 400;
                baseResult.Msg = "没有找到当前职员编号";
                return Json(baseResult);
            }

            if(this.dbContextFactory.DbContext.PermissionGroup.Where(m => m.ID == permissionGroupID&&m.Status!=-1).Select(m => m.ID).FirstOrDefault()==0)
            {
                baseResult.State = 400;
                baseResult.Msg = "没有找到当前选择的权限组";
                return Json(baseResult);
            }

            if(status==1)
            {
                UserPermissionGroup infoUserPermissionGroup=this.dbContextFactory.DbContext.UserPermissionGroup.Where(m => m.EmpID == empID && m.PermissionGroupID == permissionGroupID).FirstOrDefault();
                if(infoUserPermissionGroup!=null)
                {
                    if(infoUserPermissionGroup.Status==-1)
                    {
                        this.dbContextFactory.DbContext.UserPermissionGroup.Where(m => m.EmpID == empID && m.PermissionGroupID == permissionGroupID).Update(m => new UserPermissionGroup() { Status = 1,CreateDateTime=DateTime.Now });
                    }
                }
                else
                {
                    infoUserPermissionGroup = new UserPermissionGroup();
                    infoUserPermissionGroup.CreateDateTime = DateTime.Now;
                    infoUserPermissionGroup.EmpID = empID;
                    infoUserPermissionGroup.PermissionGroupID = permissionGroupID;
                    infoUserPermissionGroup.Status = 1;
                    this.dbContextFactory.DbContext.UserPermissionGroup.Add(infoUserPermissionGroup);

                }
            }
            else
            {
                this.dbContextFactory.DbContext.UserPermissionGroup.Where(m => m.EmpID == empID && m.PermissionGroupID == permissionGroupID).Delete();
            }

            this.dbContextFactory.DbContext.SaveChanges();

            return Json(baseResult);
        }


        [MyActionFilter("205003", "职员管理")]
        public IActionResult Show(string empID)
        {
            var infoEmployee= this.dbContextFactory.DbContext.Employee.Where(m => m.EmpID == empID).FirstOrDefault();
            ViewBag.Positions = this.dbContextFactory.DbContext.EmployeePosition.Where(m => m.EmpID == empID).ToList();
            return View(infoEmployee);
        }

    }
}